from sqlite3 import Date
from xmlrpc.client import DateTime
from fastapi import FastAPI,Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import datetime

roomList=[]#store roomlist
app=FastAPI()
idNum = 0 #add an id for each room
hisId=0#add an hisId for hisData


class RoomInfo(BaseModel):
    rid:int=None
    roomName:str
    idCard:str
    personName:str
    phone:str
    waterNumber:str
    electricNumber:str
    moveInDate:str
    roomHisInfo:list=[]
    modifyDate:Date=None


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/roomList")#get roomlist
async  def  getRoomList():
    return roomList

@app.get("/roomList/{rid}")#get roomInfo
async def getRoomData(rid:int):
    #find the item in roomList
    global roomList
    i=0
    for item in roomList:
        if(item.rid==rid):
            break
        i+=1
    return roomList[i]

@app.put("/roomList/{rid}")#update roomInfo
async def update_room(data:RoomInfo):
    #find the item in roomList
    global roomList,hisId;
    i=0
    for item in roomList:
        if(item.rid==data.rid):
            break
        i+=1
    
    #生成历史元数据hisData
    roomHisInfo=roomList[i].roomHisInfo#把上次房间的历史数据存起来
    hisData=roomList[i];#把上次的房间数据放到一个变量中
    hisData.modifyDate=datetime.date.today();#增加这个变量的时间属性
    del hisData.roomHisInfo#删除这个变量的历史信息属性
    roomHisInfo.append(hisData)

    #更新房间数据
    roomList[i]=data;#把本次提交的数据更新到房间列表中
    roomList[i].roomHisInfo=roomHisInfo;#把新的历史数据存到roomHisInfo属性
    
    return roomList[i]

@app.post("/roomList/add_room")#add a room
async def add_room(data:RoomInfo):
    global idNum
    data.rid=idNum
    idNum+=1
    data.roomHisInfo=[]
    roomList.append(data)
    print(roomList)
    return roomList

@app.delete("/roomList/{rid}")#delete an room
async def delete_room(rid:int):
    global roomList
    i=0
    for item in roomList:
        if(item.rid==rid):
            break
        i+=1
    roomList.pop(i)